package com.tdk.mybatisplus.demo.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

/**
 * <p>
 * DatabaseInit
 * </p>
 *
 * @author: taodingkai
 * @modified:
 * @since: 2022/8/9 18:11
 */
@Component
@Slf4j
@Order(-1)
public class DatabaseInit {
    @Value("${spring.flyway.init-databse-sql:CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci}")
    private String initDatabseSql;
    @Autowired
    private DynamicDataSourceConfig dynamicDataSourceConfig;

    @PostConstruct
    public void init() {
        dynamicDataSourceConfig.getDatasource().forEach((key, value) -> {
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            try {
                String driverClassName = value.get("driver-class-name");
                String url = value.get("url");
                String username = value.get("username");
                String password = value.get("password");
                url = url.substring(0, url.indexOf("?"));
                String database = url.substring(url.lastIndexOf("/") + 1);
                url = url.substring(0, url.lastIndexOf("/"));
                //Class.forName(driverClassName);
                Class.class.getDeclaredMethod("forName", String.class).invoke(null,driverClassName);
                //获取连接
                connection = DriverManager.getConnection(url, username, password);
                connection.setAutoCommit(false);
                //获取操作数据库的预处理对象
                preparedStatement = connection.prepareStatement(String.format(initDatabseSql, database));
                //执行SQL语句
                preparedStatement.executeUpdate();
            } catch (Exception e) {
                log.error("创建数据库异常", e);
            } finally {
                //释放资源
                try {
                    if (Objects.nonNull(preparedStatement)) {
                        preparedStatement.close();
                    }
                    if (Objects.nonNull(connection)) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    log.error("关闭资源异常", e);
                }
            }
        });
    }

    @Bean
    DataSourceAutoConfiguration dataSourceAutoConfiguration() {
        return new DataSourceAutoConfiguration();
    }
}
